package com.dqhl.community.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.ExchangeCouponAdapter;
import com.dqhl.community.adapter.PayMentCouponAdapter;
import com.dqhl.community.adapter.ShoppingCarPayAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.ExchangeCoupon;
import com.dqhl.community.model.GoodsNumberSerializableMap;
import com.dqhl.community.model.PayMentCoupon;
import com.dqhl.community.model.ShopCartBean;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.DoubleOperation;
import com.dqhl.community.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by cheng on 2016/9/20.
 * 购物车确认账单
 */
public class ShoppingCarOrderActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private LinearLayout ll_add_gouwuche;
    private ImageView iv_top_back;
    private TextView tv_top_title;
    private TextView tv_shopping_allmoney;

    private ListView lv_goods;
    private ShoppingCarPayAdapter shoppingCarPayAdapter;
    private List<ShopCartBean> shopCartBeanList;
    private String strTotal; //需支付的金额
    private List<String> goods_idList; //需要付款的商品id
    private TextView tv_account; //确认付款
    private TextView tv_address;
    //支付
    private RadioGroup radioGroup;
    private RadioButton rb_weixin;
    private RadioButton rb_alipay;
    private RadioButton rb_cash;
    private String payment_method = ""; //线上还是线下支付方式
    private String payType = "";
    private String payGoodsId = "";//商品ID
    private String order_long = "";//长的name  订单号
    private JSONObject goodsNumberJsonObject;
    private View view_bottom;
    private TextView tv_order;
    private ListView lv_payment;
    private ListView lv_exchange;
    private PayMentCouponAdapter payMentCouponAdapter;
    private List<PayMentCoupon> payMentCouponList;
    private ExchangeCouponAdapter exchangeCouponAdapter;
    private List<ExchangeCoupon> exchangeCouponList;
    private TextView tv_current_integral;
    private String userId;
    private double tempMoney1;
    private double tempMoney2;
    private PayMentCoupon payMentCoupon_coupon;
    private ExchangeCoupon payMentCoupon_exchange;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_car_payment);
        context = this;

        initView();
        initData();
        //优惠券接口
        getCoupon();
//        getExchangeCoupon();
    }

    private void initView() {
        shopCartBeanList = (List<ShopCartBean>) getIntent().getSerializableExtra("goods_list");
        goods_idList = (List<String>) getIntent().getSerializableExtra("goods_id");
        Dlog.e("GGgoods_idList:" + goods_idList.toString());
        strTotal = getIntent().getStringExtra("price");
        GoodsNumberSerializableMap goodsNumberSerializableMap = (GoodsNumberSerializableMap) getIntent().getExtras().get("map");
        Map<String, String> goodsNumberMap = goodsNumberSerializableMap.getMap();
        Dlog.e("map:" + goodsNumberMap.toString());
        goodsNumberJsonObject = new JSONObject();
        for (Map.Entry<String, String> entry : goodsNumberMap.entrySet()) {
            try {
                goodsNumberJsonObject.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Dlog.e("jsonObject:" + goodsNumberJsonObject.toString());

        Dlog.e("strTotal:" + strTotal);

        iv_top_back = (ImageView) findViewById(R.id.iv_top_back);
        iv_top_back.setVisibility(View.VISIBLE);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("提交订单");
        ll_add_gouwuche = (LinearLayout) findViewById(R.id.ll_add_gouwuche);
        ll_add_gouwuche.setVisibility(View.GONE);
        (view_bottom) = findViewById(R.id.view_botoom);
        view_bottom.setVisibility(View.GONE);
        (tv_order) = (TextView) findViewById(R.id.tv_account);
        tv_order.setText("确认账单");
        tv_shopping_allmoney = (TextView) findViewById(R.id.tv_shopping_allmoney);
        tv_shopping_allmoney.setText("￥" + strTotal);
        tv_account = (TextView) findViewById(R.id.tv_account);
        tv_account.setText("确认付款");
        tv_address = (TextView) findViewById(R.id.tv_address);
        String strAddress = spUserInfo.getString(Constant.ADDRESS, "");
        tv_address.setText(strAddress);
        (lv_payment) = (ListView) findViewById(R.id.lv_payment);
        lv_exchange = (ListView) findViewById(R.id.lv_exchange);
        tv_current_integral = (TextView) findViewById(R.id.tv_current_integral);

        lv_goods = (ListView) findViewById(R.id.lv_goods);
        shoppingCarPayAdapter = new ShoppingCarPayAdapter(this, shopCartBeanList);
        lv_goods.setAdapter(shoppingCarPayAdapter);


        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        rb_weixin = (RadioButton) findViewById(R.id.rb_weixin);
        rb_alipay = (RadioButton) findViewById(R.id.rb_alipay);
        rb_cash = (RadioButton) findViewById(R.id.rb_cash);
        iv_top_back.setOnClickListener(this);
        tv_account.setOnClickListener(this);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_weixin:
                        payment_method = "1";
                        payType = "微信";
                        break;
                    case R.id.rb_alipay:
                        payment_method = "1";
                        payType = "支付宝";
                        break;
                    case R.id.rb_cash:
                        payment_method = "2";
                        break;
                }
            }
        });
    }

    private void initData() {
        userId = user.getUserid();
        tv_current_integral.setText(user.getIntegral());
        tempMoney2 = tempMoney1 = Double.parseDouble(getIntent().getStringExtra("price"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.tv_account: //
                doCommit();
                break;
        }
    }

    /**
     * 生成订单
     */
    private void doCommit() {
        Dlog.e(payType + "GG付款方式 " + payment_method);
        showCustomLoadBar("加载中");
        RequestParams params = new RequestParams(Config.Api.supermarketCartSell);
        params.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
        params.addBodyParameter("total", strTotal); //总金额
        params.addBodyParameter("payment_method", payment_method); //支付方式(1代表线上支付,2代表货到付款)
        params.addBodyParameter("goods", goods_idList.toString()); // 商品ID 为json格式数组.
        params.addBodyParameter("number", goodsNumberJsonObject.toString());
        if ("微信".equals(payType)) {
            params.addBodyParameter("payment_platform", "微信");
        } else if ("支付宝".equals(payType)) {
            params.addBodyParameter("payment_platform", "支付宝");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG订单详情返回result:" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    //给我返回orderID,再去获取微信支付信息，调用支付
                    payGoodsId = JsonUtils.getInfo(data, "name");
                    order_long = JsonUtils.getInfo(data, "order_id");
                    Dlog.e("GGorderIDd  " + payGoodsId);
                    Bundle bundle = new Bundle();
                    bundle.putString("type", payType);
                    bundle.putString("order_id", payGoodsId);
                    bundle.putString("order_long", order_long);
                    bundle.putSerializable("goods_list", (Serializable) shopCartBeanList);
                    bundle.putSerializable("goods_id", (Serializable) goods_idList);
                    bundle.putSerializable("coupon", payMentCoupon_coupon);
                    bundle.putSerializable("exchange", payMentCoupon_exchange);
                    bundle.putString("price", strTotal);
                    overlay(ShoppingCartPayActivity.class, bundle);
//
                } else {
                    toast("付款失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 优惠券接口
     */
    private void getCoupon() {
        showCustomLoadBar("加载中");
        Dlog.e(goods_idList + " GG " + goodsNumberJsonObject.toString());
        RequestParams params = new RequestParams(Config.Api.lookupCoupon);
        params.addBodyParameter("userid", userId);
        params.addBodyParameter("goods", goods_idList.toString());
        params.addBodyParameter("number", goodsNumberJsonObject.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG优惠券" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    payMentCouponList = JSON.parseArray(data, PayMentCoupon.class);
                    Dlog.e(payMentCouponList.toString());
                    (payMentCouponAdapter) = new PayMentCouponAdapter(context, payMentCouponList,
                            new PayMentCouponAdapter.OnRadioButtonCheckedListener() {
                                @Override
                                public void onSelectedPosition(int positon) {
                                    Dlog.e("coupon_id " + payMentCouponList.get(positon).getId());
                                    getExchangeCoupon(payMentCouponList.get(positon).getId());
                                    payMentCoupon_coupon = payMentCouponList.get(positon);
                                    tempMoney1 = Double.parseDouble(getIntent().getStringExtra("price"));
                                    if ("1".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Double denomination = Double.parseDouble(payMentCouponList.get(positon).getDenomination().substring(1, payMentCouponList.get(positon).getDenomination().length() - 1));
                                        Dlog.e("deno=" + deno + ";denomination:" + denomination);

                                        Double money = tempMoney1;
                                        if (money >= denomination) {
                                            money = money - deno;
                                        }
                                        tempMoney2 = money;
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    } else if ("2".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("折", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney1;
                                        money = DoubleOperation.div(DoubleOperation.mul(money, deno), 10.0, 1);
                                        tempMoney2 = money;
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    } else if ("3".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney1;
                                        money = money - deno;

                                        tempMoney2 = money;
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    }

                                }

                                @Override
                                public void onUnSelectedPosition(int positon) {
                                    Dlog.e("unselected:" + positon);
//                                    if ("1".equals(payMentCouponList.get(positon).getCondition())) {
//                                        strTotal = String.valueOf(tempMoney1);
//                                        tv_shopping_allmoney.setText("￥" + strTotal);
//                                    } else if ("2".equals(payMentCouponList.get(positon).getCondition())) {
//                                        strTotal = String.valueOf(tempMoney1);
//                                        tv_shopping_allmoney.setText("￥" + strTotal);
//                                    } else if ("3".equals(payMentCouponList.get(positon).getCondition())) {
//                                        strTotal = String.valueOf(tempMoney1);
//                                        tv_shopping_allmoney.setText("￥" + strTotal);
//                                    }
                                    payMentCoupon_coupon = null;
                                    tempMoney2 = tempMoney1;
                                    strTotal = String.valueOf(tempMoney1);
                                    tv_shopping_allmoney.setText("￥" + strTotal);
                                }
                            });
                    payMentCouponAdapter.notifyDataSetChanged();
                    lv_payment.setAdapter(payMentCouponAdapter);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Dlog.e("GGonError" + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 积分
     */
    private void getExchangeCoupon(String coupon_id) {
        RequestParams params = new RequestParams(Config.Api.lookupExchange);
        params.addBodyParameter("userid", userId);
        params.addBodyParameter("coupon", coupon_id);
        params.addBodyParameter("goods", goods_idList.toString());
        params.addBodyParameter("number", goodsNumberJsonObject.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (0 == errCode) {
                    exchangeCouponList = JSON.parseArray(data, ExchangeCoupon.class);
                    exchangeCouponAdapter = new ExchangeCouponAdapter(context, exchangeCouponList,
                            new ExchangeCouponAdapter.OnRadioButtonCheckedListener() {
                                @Override
                                public void onSelectedPosition(int positon) {
                                    payMentCoupon_exchange = exchangeCouponList.get(positon);
                                    Dlog.e("selected:" + positon);
                                    if ("1".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Double denomination = Double.parseDouble(payMentCouponList.get(positon).getDenomination().substring(1, payMentCouponList.get(positon).getDenomination().length() - 1));
                                        Dlog.e("deno=" + deno + ";denomination:" + denomination);
                                        Double money = tempMoney2;
                                        if (money >= denomination) {
                                            money = money - deno;
                                        }
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    } else if ("2".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("折", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney2;
                                        money = DoubleOperation.div(DoubleOperation.mul(money, deno), 10.0, 1);
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    } else if ("3".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney2;
                                        money = money - deno;
                                        if (money <= 0) {
                                            tv_shopping_allmoney.setText("￥0");
                                        } else {
                                            strTotal = String.valueOf(money);
                                            tv_shopping_allmoney.setText("￥" + strTotal);
                                        }
                                    }
                                }

                                @Override
                                public void onUnSelectedPosition(int positon) {
                                    Dlog.e("unselected:" + positon);
                                    payMentCoupon_exchange = null;
                                    strTotal = String.valueOf(tempMoney2);
                                    tv_shopping_allmoney.setText("￥" + strTotal);
                                }
                            });
                    exchangeCouponAdapter.notifyDataSetChanged();
                    lv_exchange.setAdapter(exchangeCouponAdapter);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
